/**
 * @Title: ShopOrderController.java
 * @Package com.lemon.controller.cityRun
 * @Description: (一句话阐述):
 * @author Ran_cc
 * @date 2018年10月26日
 * @version V1.0
 */
package com.lemon.controller.cityRun;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.lemon.conf.MyException;
import com.lemon.conf.MyInterceptor.LoginRequired;
import com.lemon.conf.content.IdTypeHandler;
import com.lemon.controller.BaseController;
import com.lemon.model.cityRun.CrShopOrderComment;
import com.lemon.model.cityRun.CrShopOrderGoods;
import com.lemon.model.cityRun.CrShopOrders;
import com.lemon.model.cityRun.CrShops;
import com.lemon.service.cityRun.CrShopOrderService;
import com.lemon.service.cityRun.CrShopsService;
import com.lemon.service.cityRun.ShopPrintService;
import com.lemon.utils.CityRunUtils;
import com.lemon.utils.HttpUtil;
import com.lemon.utils.ReqResult;
import com.lemon.utils.StringUtil;
import com.lemon.utils.sval.StaticValues;

/**
 * <p>
 * Title: ShopOrderController
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author Ran_cc
 * @date 2018年10月26日
 * @版本 V 1.0
 */
@RestController
@RequestMapping("/order")
public class ShopOrderController extends BaseController {
	@Resource
	private CrShopOrderService orderService;

	@Resource
	private CrShopsService sService;

	@Resource
	private ShopPrintService printService;

	////////////////////////////商品信息///////////////////////////////////
	/**
	 * <b>Description:<blockquote> 查询订单列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月23日
	 */
	@RequestMapping("/getOrdersList")
	public ReqResult getOrdersList(@ModelAttribute CrShopOrders order , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			CrShopOrders or = new CrShopOrders();
			//pageNum=1,shopId=mhfu,status=2,type=1,pageSize=10
			or.setPageNum(order.getPageNum());
			or.setPageSize(order.getPageSize());
			or.setShopId(order.getShopId());
			or.setType(order.getType());

			if (StringUtil.isNotBlank(order.getStartDate())) {
				order.setStatus(null);
				or.setWhere(" and a.status = 5  and a.create_time like '%?%' " , order.getStartDate());
			} else {
				or.setWhere(" and a.status != 0  ");
			}

			if (order.getStatus() != null && 3 == order.getStatus()) {
				or.setWhereAppend(" and (a.status = 3 or a.status = 31 or a.status = 32  ) ");
			} else if (order.getStatus() != null && (4 == order.getStatus())) {
				or.setWhere(" and a.status =4  ");
				//				or.setWhereAppend(" and ( a.create_time >= ? )" , CityRunUtils.getBusineDateString());
				//						order.setWhereAppend(" and  (a.status != 0 and  a.status != 4  and a.status != 5 )");
			} else if (order.getStatus() != null && 5 == order.getStatus()) {
				or.setWhereAppend(" and ( a.status = 51 or a.status = 5  or a.status = 52 or a.status = 6  ) ");
				//				or.setWhereAppend(" and ( a.create_time >= ? )" , CityRunUtils.getBusineDateString());
			} else if (order.getStatus() != null && 2 == order.getStatus()) {
				or.setWhere(" and a.status = 2  ");
				//				or.setWhereAppend(" and ( a.create_time >= ? )" , CityRunUtils.getBusineDateString());
			} else {
				or.setWhereAppend(" and ( a.create_time >= ? )" , CityRunUtils.getBusineDateString());
				or.setWhereAppend(" or  (a.status != 0 and  a.status != 4  and a.status != 5 ))");
			}

			log.info(" order status : {}" , order.getStatus());
			or.setOrderBy(" order by a.create_time desc");
			List<CrShopOrders> list = orderService.selectListBySelective(or);
			boolean flag = true;
			while (flag) {
				if (list.size() == 0) {
					flag = false;
					break;
				}
				System.out.println(list.size());
				for (CrShopOrders ord : list) {

					log.info("开始判断状态:{}," , ord.getStatus());

					int time = 2;
					if (ord.getType() == 2) {
						time = 4;
					}
					if ((ord.getStatus() == 3 || ord.getStatus() == 31 || ord.getStatus() == 32)
							&& StringUtil.addDateHour(ord.getCreateTime() , time).getTime() < new Date().getTime()) {
						Map<String , String> map = new HashMap<String , String>();
						map.put("id" , ord.getId());
						map.put("status" , 4 + "");
						map.put("shopId" , order.getShopId());
						String doPost = HttpUtil.doPost(StaticValues.ROOT_RUL + "cityRun/order/updateOrderInfo.do" ,
								map);
						log.info("app端请求拒单接口,请求服务端接口如果付款的话,将会把钱退还至用户微信零钱中");
						log.info(doPost);
						try {
							JSONObject parse = (JSONObject) JSONObject.parse(doPost);
							if ("1000".equals(parse.get("resultCode"))) {
								//list.remove(list.get(i));
							}
						} catch (Exception e) {
						}
						//					boolean remove = list.remove(list.get(i));
						boolean remove = list.remove(ord);
						log.info(remove + "");
						flag = true;
						break;
					} else if (ord.getStatus() == 2
							&& StringUtil.addDateMinute(ord.getCreateTime() , 15).getTime() < new Date().getTime()) {
						CrShopOrders ss = new CrShopOrders();
						ss.setId(ord.getId());
						ss.setStatus(52);
						Map<String , String> map = new HashMap<String , String>();
						map.put("id" , ord.getId());
						map.put("status" , 5 + "");
						map.put("shopId" , order.getShopId());
						String doPost = HttpUtil.doPost(StaticValues.ROOT_RUL + "cityRun/order/updateOrderInfo.do" ,
								map);
						log.info("app端请求拒单接口,请求服务端接口如果付款的话,将会把钱退还至用户微信零钱中");
						log.info(doPost);
						//list.remove(list.get(i));
						try {
							JSONObject parse = (JSONObject) JSONObject.parse(doPost);
							if ("1000".equals(parse.getString("resultCode"))) {
								boolean remove = list.remove(ord);
								flag = true;
								break;
							}
						} catch (Exception e) {
						}
					}
					flag = false;
				}
			}

			log.info(list.size() + "");

			for (CrShopOrders ord : list) {
				String id = ord.getId();
				CrShopOrderGoods ogo = new CrShopOrderGoods();
				ogo.setOrderId(id);
				List<CrShopOrderGoods> li = orderService.selectOrderGoodsListBySelective(ogo);
				ord.setList(li);
			}
			/*
			 * for (int i = 0; i < list.size(); i++) {
			 * CrShopOrders ord = list.get(i);
			 * log.info("{}开始判断状态:{}," , i, ord.getStatus());
			 * boolean remove = list.remove(list.get(i));
			 * int time = 2;
			 * if (order.getType() == 2) {
			 * time = 4;
			 * }
			 * if (ord.getStatus() == 3
			 * && StringUtil.addDateHour(ord.getCreateTime() , time).getTime() < new Date().getTime()) {
			 * Map<String , String> map = new HashMap<String , String>();
			 * map.put("id" , ord.getId());
			 * map.put("status" , 4 + "");
			 * map.put("shopId" , order.getShopId());
			 * String doPost = HttpUtil.doPost("https://chengpao8.com/cityRun/order/updateOrderInfo.do" , map);
			 * log.info("app端请求拒单接口,请求服务端接口如果付款的话,将会把钱退还至用户微信零钱中");
			 * log.info(doPost);
			 * try {
			 * JSONObject parse = (JSONObject) JSONObject.parse(doPost);
			 * if ("1000".equals(parse.get("resultCode"))) {
			 * //list.remove(list.get(i));
			 * }
			 * } catch (Exception e) {
			 * }
			 * // boolean remove = list.remove(list.get(i));
			 * log.info(remove + "");
			 * continue;
			 * } else if (ord.getStatus() == 2
			 * && StringUtil.addDateMinute(ord.getCreateTime() , 15).getTime() < new Date().getTime()) {
			 * CrShopOrders ss = new CrShopOrders();
			 * ss.setId(ord.getId());
			 * ss.setStatus(52);
			 * Map<String , String> map = new HashMap<String , String>();
			 * map.put("id" , ord.getId());
			 * map.put("status" , 52 + "");
			 * map.put("shopId" , order.getShopId());
			 * String doPost = HttpUtil.doPost("https://chengpao8.com/cityRun/order/updateOrderInfo.do" , map);
			 * log.info("app端请求拒单接口,请求服务端接口如果付款的话,将会把钱退还至用户微信零钱中");
			 * log.info(doPost);
			 * //list.remove(list.get(i));
			 * try {
			 * JSONObject parse = (JSONObject) JSONObject.parse(doPost);
			 * if ("1000".equals(parse.get("resultCode"))) {
			 * list.remove(list.get(i));
			 * continue;
			 * }
			 * } catch (Exception e) {
			 * }
			 * }
			 * String id = ord.getId();
			 * CrShopOrderGoods ogo = new CrShopOrderGoods();
			 * ogo.setOrderId(id);
			 * List<CrShopOrderGoods> li = orderService.selectOrderGoodsListBySelective(ogo);
			 * list.get(i).setList(li);
			 * }
			 */
			log.info(list.size() + "");
			reqResult.setReturnResult(list.size() == 0 ? null : list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	@RequestMapping("/getOrdersByOrder")
	public ReqResult getOrdersByOrder(@ModelAttribute CrShopOrders order , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			List<CrShopOrders> list = orderService.selectListBySelective(order);
			for (int i = 0; i < list.size(); i++) {
				CrShopOrders ord = list.get(i);
				String id = ord.getId();
				CrShopOrderGoods ogo = new CrShopOrderGoods();
				ogo.setOrderId(id);
				List<CrShopOrderGoods> li = orderService.selectOrderGoodsListBySelective(ogo);
				list.get(i).setList(li);
			}
			reqResult.setReturnResult(list.size() > 0 ? list.get(0) : null);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 修改订单信息
	 * </blockquote></b>
	 * 
	 * @Title: updateOrderInfo
	 * @param order
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月14日
	 */
	@RequestMapping("/updateOrderInfo.do")
	public Object updateOrderInfo(@ModelAttribute CrShopOrders order , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		String doPost = "";
		try {
			//int list = orderService.updateOrderInfo(order);
			//判断订单的状态 ,如果是接单  
			//			if (order.getStatus() == 3) { //接单
			/*
			 * String string = RedisUtil.get("cityRun:set:set_" + order.getShopId());
			 * if (StringUtil.isNotBlank(string)) {
			 * JSONObject js = (JSONObject) JSONObject.parse(string);
			 * //在判断是否自动打印
			 * if (1 == js.getIntValue("printAuto")) {
			 * try {
			 * printService.printerInfo(order.getShopId() , order.getId());
			 * } catch (Exception e) {
			 * MyException.writeErr(e , "打印机打印订单异常,订单编号:" + order.getOrderNo());
			 * }
			 * }
			 * }
			 */
			//			} else if (order.getStatus() == 5) {
			try {
				Map<String , String> map = new HashMap<String , String>();
				map.put("id" , order.getId());
				map.put("status" , order.getStatus() + "");
				map.put("shopId" , order.getShopId());
				doPost = HttpUtil.doPost(StaticValues.ROOT_RUL + "cityRun/order/updateOrderInfo.do" , map);
				log.info("app端请求拒单接口,请求服务端接口如果付款的话,将会把钱退还至用户微信零钱中");
				log.info(doPost);
			} catch (Exception e) {
				MyException.writeErr(e , "app端请求拒单接口,异常");
			}
			//			}
			reqResult.setReturnResult(1);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		//		return reqResult;
		return JSONObject.parse(doPost);
	}

	@RequestMapping("/selectOrderProfitToday")
	public ReqResult selectOrderProfitToday(@ModelAttribute CrShopOrders order , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			//			order.setWhere(" and a.status  = 4 ");
			//order.setOrderBy(" order by a.create_time desc");
			order.setWhereAppend(" and ( a.status  = 4 or a.status = 3 or a.status = 32 or a.status = 31 ) ");
			order.setStartDate(CityRunUtils.getBusineDateString());
			Map<String , Object> list = orderService.selectOrderProfitToday(order);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	///////////////////订单评论////////////////////////
	/**
	 * <b>Description:<blockquote> 查询评价列表
	 * </blockquote></b>
	 * 
	 * @Title: getGoodsList
	 * @param go
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年10月23日
	 */
	@RequestMapping("/getOrderCommentList")
	public ReqResult getOrderCommentList(@ModelAttribute CrShopOrderComment comment , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			//星级查询 
			String star = request.getParameter("starStr");
			//有无内容
			String hsa = request.getParameter("hasCon");

			StringBuffer buffer = new StringBuffer();
			if ("1".equals(hsa)) {
				buffer.append(" and a.content is not null");
			} else if ("2".equals(hsa)) {
				buffer.append(" and a.content is null");
			}

			if (StringUtil.isNotBlank(star)) {
				buffer.append(" and a.comment_star in (");
				buffer.append(star);
				buffer.append(")");
			}
			//时间条件
			String s = request.getParameter("startTime");
			String e = request.getParameter("endTime");
			if (StringUtil.isNotBlank(s) && StringUtil.isNotBlank(e)) {
				buffer.append(" and a.create_time  > '");
				buffer.append(s);
				buffer.append("' and a.create_time  < '");
				buffer.append(e);
				buffer.append("' ");
			} else if (StringUtil.isNotBlank(s)) {
				buffer.append(" and a.create_time  > '");
				buffer.append(s);
				buffer.append("' ");
			} else if (StringUtil.isNotBlank(e)) {
				buffer.append(" and a.create_time  < '");
				buffer.append(e);
				buffer.append("' ");
			}
			String spid = request.getParameter("shopId");
			buffer.append(" and b.shop_id = ");
			buffer.append(IdTypeHandler.decode(spid));

			buffer.append(" and a.status != 0 ");
			comment.setWhere(buffer.toString());
			comment.setOrderBy(" order by a.create_time desc");
			List<CrShopOrderComment> list = orderService.selectCommentsListBySelective(comment);
			for (int i = 0; i < list.size(); i++) {
				CrShopOrderGoods ogo = new CrShopOrderGoods();
				ogo.setOrderId(list.get(i).getId());
				List<CrShopOrderGoods> li = orderService.selectOrderGoodsListBySelective(ogo);
				list.get(i).setList(li);
			}
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 修改订单评论
	 * </blockquote></b>
	 * 
	 * @Title: updateOrderCommentList
	 * @param comment
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月1日
	 */
	@LoginRequired
	@RequestMapping("/updateOrderCommentList.do")
	public ReqResult updateOrderCommentList(@ModelAttribute CrShopOrderComment comment , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			int row = orderService.updateCommentBySelective(comment);
			reqResult.setReturnResult(row);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 查询财务对账每天的订单收入
	 * </blockquote></b>
	 * 
	 * @Title: updateOrderCommentList
	 * @param comment
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月1日
	 */
	@LoginRequired
	@RequestMapping("/getOrderProfitList")
	public ReqResult getOrderProfitList(@ModelAttribute CrShopOrders orders , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {

			String star = request.getParameter("startTime");
			String end = request.getParameter("endTime");
			StringBuffer buffer = new StringBuffer();

			if (StringUtil.isNotBlank(star) && StringUtil.isNotBlank(end)) {
				buffer.append(" and temp.date >='");
				buffer.append(star);
				buffer.append("' and temp.date <='");
				buffer.append(end);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(star)) {
				buffer.append(" and temp.date >='");
				buffer.append(star);
				buffer.append("'");
			} else if (StringUtil.isNotBlank(end)) {
				buffer.append(" and temp.date <='");
				buffer.append(end);
				buffer.append("'");
			}

			CrShops shops = sService.selectShopById(orders.getShopId());
			//计算店铺注册时间到今天的天数
			int days = StringUtil.getDistanceDays(shops.getCreateTime() , new Date());
			orders.setProDays(days + "");
			orders.setStartDate(StringUtil.DateToString(shops.getCreateTime() , 0));
			orders.setWhere(buffer.toString());
			List<Map<String , Object>> list = orderService.getOrderProfitList(orders);
			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	/**
	 * <b>Description:<blockquote> 获得商家首页的统计数据
	 * </blockquote></b>
	 * 
	 * @Title: getShopTodayFirgit
	 * @param orders
	 * @param request
	 * @param response
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月10日
	 */
	@RequestMapping("/getShopTodayFirgit")
	public ReqResult getShopTodayFirgit(@ModelAttribute CrShopOrders orders , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			Date date = StringUtil.StringToDate(StaticValues.TODAY_TIME() , 4);
			Date date2 = new Date();
			if (date.getTime() > date2.getTime()) {
				orders.setCreateTime(StringUtil.StringToDate(StaticValues.YESTERDAY_TIME() , 4));
			} else {
				orders.setCreateTime(StringUtil.StringToDate(StaticValues.TODAY_TIME() , 4));
			}

			Map<String , Object> map = orderService.getShopTodayFirgit(orders);
			reqResult.setReturnResult(map);
		} catch (Exception e) {
			reqResult.setReturnResult("" , ReqResult.code_error);
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	@RequestMapping("/getOrdersById")
	public ReqResult getOrdersById(@ModelAttribute CrShopOrders order , HttpServletRequest request ,
			HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			List<CrShopOrders> list = orderService.selectListBySelective(order);
			for (int i = 0; i < list.size(); i++) {
				CrShopOrders ord = list.get(i);
				String id = ord.getId();
				CrShopOrderGoods ogo = new CrShopOrderGoods();
				ogo.setOrderId(id);
				List<CrShopOrderGoods> li = orderService.selectOrderGoodsListBySelective(ogo);
				list.get(i).setList(li);
			}
			if (list.size() > 0) {

				CrShopOrders orders = list.get(0);
				CrShopOrders or = new CrShopOrders();
				or.setShopId(orders.getShopId());
				or.setWhere(" and a.create_time >= ? " , CityRunUtils.getBusineDateString());
				int coun = orderService.selectCountBySelective(or);
				orders.setSort(coun);
				//				CityRunUtils.setOrderTimesCookie(list.get(0).getShopId());
				//				System.out.println("done!");
				/*
				 * CrShopOrders orders = list.get(0);
				 * CrShopOrders or = new CrShopOrders();
				 * or.setShopId(orders.getShopId());
				 * or.setWhere(" and a.create_time >= ? " , CityRunUtils.getBusineDateString());
				 * int coun = orderService.selectCountBySelective(or);
				 * orders.setSort(coun);
				 * //获取打印机
				 * CrShopPrinter cp = new CrShopPrinter();
				 * cp.setShopId(orders.getShopId());
				 * cp.setStatus(1);
				 */

				/*
				 * List<CrShopPrinter> listPrinters = shopsService.selectPrintListBySelective(cp);
				 * if (listPrinters.size() > 0) {
				 * CrShopPrinter p = listPrinters.get(0);
				 * String printer = PrinterUtils.printer(orders , p.getDevNo() , p.getDevSecretKey() , 1 , 1);
				 * System.out.println(printer);
				 * }
				 */

				/*
				 * String string = RedisUtil.get("cityRun:print:print_" + orders.getShopId());
				 * if (StringUtil.isNotBlank(string)) {
				 * JSONObject js = (JSONObject) JSONObject.parse(string);
				 * JSONArray jsonArray = js.getJSONArray("list");
				 * jsonArray.add(orders);
				 * js.put("list" , jsonArray);
				 * RedisUtil.set("cityRun:print:print_" + orders.getShopId() , js);
				 * } else {
				 * JSONObject js = new JSONObject();
				 * JSONArray arr = new JSONArray();
				 * arr.add(orders);
				 * js.put("list" , arr);
				 * RedisUtil.set("cityRun:print:print_" + orders.getShopId() , js);
				 * }
				 */
				reqResult.setReturnResult(orders);
				return reqResult;
			}

			reqResult.setReturnResult(list);
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
		return reqResult;
	}

	public static void main(String[] args) {
		List<String> ss = new ArrayList<String>();
		ss.add("a");
		ss.add("b");
		ss.add("c");
		ss.add("d");
		ss.add("e");
		System.err.println(ss.size());
		for (int i = 0; i < ss.size(); i++) {

			String string = ss.get(i);
			if ("b".equals(string)) {
				ss.remove(ss.get(i));
				continue;
			}

		}
		System.err.println(ss.size());
	}

}
